import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Paper,
  TextField,
  Button,
  MenuItem,
  FormControl,
  InputLabel,
  Select,
  Switch,
  FormControlLabel,
  Alert,
  CircularProgress,
  Chip,
  Stepper,
  Step,
  StepLabel,
} from '@mui/material';
import { ArrowBack as BackIcon, Save as SaveIcon } from '@mui/icons-material';
import { useConnectionStore } from '../../stores/connectionStore';
import { useDomainStore } from '../../stores/domainStore';

interface DomainFormData {
  name: string;
  memory: number;
  vcpus: number;
  disk_path: string;
  disk_size: number;
  disk_bus: 'virtio' | 'sata' | 'scsi';
  architecture: 'x86_64' | 'aarch64';
  boot_mode: 'bios' | 'uefi';
  network_mode: 'network' | 'bridge' | 'user';
  network_name: string;
  os_variant: string;
  auto_start: boolean;
}

const DomainCreate: React.FC = () => {
  const navigate = useNavigate();
  const currentConnection = useConnectionStore(state => state.currentConnection);
  const { createDomain, loading, error, clearError } = useDomainStore();
  
  const [activeStep, setActiveStep] = useState(0);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formData, setFormData] = useState<DomainFormData>({
    name: '',
    memory: 2048,
    vcpus: 2,
    disk_path: '',
    disk_size: 20,
    disk_bus: 'virtio',
    architecture: 'x86_64',
    boot_mode: 'bios',
    network_mode: 'network',
    network_name: 'default',
    os_variant: '',
    auto_start: true,
  });

  const steps = ['基本信息', '硬件配置', '存储配置', '网络配置'];

  const handleInputChange = (field: keyof DomainFormData, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleNext = () => {
    setActiveStep((prevStep) => prevStep + 1);
  };

  const handleBack = () => {
    setActiveStep((prevStep) => prevStep - 1);
  };

  const handleSubmit = async () => {
    if (!currentConnection) return;

    setIsSubmitting(true);
    try {
      console.log('创建虚拟机数据:', formData);
      await createDomain(currentConnection, formData);
      
      // 创建成功后跳转回列表页
      navigate('/domains');
    } catch (error) {
      console.error('创建虚拟机失败:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  // const presetConfigs = { // 暂时未使用，保留供将来使用
  //   lightweight: { memory: 1024, vcpus: 1, disk_size: 10 },
  //   standard: { memory: 2048, vcpus: 2, disk_size: 20 },
  //   highPerformance: { memory: 4096, vcpus: 4, disk_size: 50 },
  // };

  if (!currentConnection) {
    return (
      <Box>
        <Typography variant="h4" component="h1" gutterBottom fontWeight="bold">
          创建虚拟机
        </Typography>
        <Alert severity="warning">
          请先选择一个连接
        </Alert>
      </Box>
    );
  }

  return (
    <Box>
      <Box display="flex" alignItems="center" mb={3}>
        <Button onClick={() => navigate('/domains')} sx={{ mr: 1, minWidth: 'auto' }}>
          <BackIcon />
        </Button>
        <Typography variant="h4" component="h1" fontWeight="bold">
          创建虚拟机
        </Typography>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={clearError}>
          {error}
        </Alert>
      )}

      <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
        {steps.map((label) => (
          <Step key={label}>
            <StepLabel>{label}</StepLabel>
          </Step>
        ))}
      </Stepper>

      <Paper sx={{ p: 4 }}>
        {/* 步骤1: 基本信息 */}
        {activeStep === 0 && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
            <TextField
              label="虚拟机名称"
              value={formData.name}
              onChange={(e) => handleInputChange('name', e.target.value)}
              fullWidth
              placeholder="例如: ubuntu-vm-01"
              helperText="虚拟机名称，建议使用描述性名称"
            />
            
            <FormControl fullWidth>
              <InputLabel>架构</InputLabel>
              <Select
                value={formData.architecture}
                onChange={(e) => handleInputChange('architecture', e.target.value)}
                label="架构"
              >
                <MenuItem value="x86_64">x86_64</MenuItem>
                <MenuItem value="aarch64">aarch64</MenuItem>
              </Select>
            </FormControl>

            <FormControl fullWidth>
              <InputLabel>启动模式</InputLabel>
              <Select
                value={formData.boot_mode}
                onChange={(e) => handleInputChange('boot_mode', e.target.value)}
                label="启动模式"
              >
                <MenuItem value="bios">BIOS (传统模式)</MenuItem>
                <MenuItem value="uefi">UEFI (现代模式)</MenuItem>
              </Select>
            </FormControl>

            <TextField
              label="操作系统类型"
              value={formData.os_variant}
              onChange={(e) => handleInputChange('os_variant', e.target.value)}
              fullWidth
              placeholder="例如: ubuntu22.04, centos8"
              helperText="用于优化虚拟机配置，可选"
            />

            <FormControlLabel
              control={
                <Switch
                  checked={formData.auto_start}
                  onChange={(e) => handleInputChange('auto_start', e.target.checked)}
                />
              }
              label="创建后自动启动"
            />
          </Box>
        )}

        {/* 步骤2: 硬件配置 */}
        {activeStep === 1 && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
            <TextField
              label="内存 (MB)"
              type="number"
              value={formData.memory}
              onChange={(e) => handleInputChange('memory', parseInt(e.target.value) || 0)}
              fullWidth
              helperText="建议至少1024MB"
            />
            
            <TextField
              label="vCPU数量"
              type="number"
              value={formData.vcpus}
              onChange={(e) => handleInputChange('vcpus', parseInt(e.target.value) || 0)}
              fullWidth
              helperText="虚拟CPU核心数"
            />

            <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
              快速配置：
            </Typography>
            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              <Chip 
                label="轻量级: 1GB RAM, 1 vCPU" 
                size="small" 
                clickable 
                onClick={() => {
                  handleInputChange('memory', 1024);
                  handleInputChange('vcpus', 1);
                }} 
              />
              <Chip 
                label="标准: 2GB RAM, 2 vCPU" 
                size="small" 
                clickable 
                onClick={() => {
                  handleInputChange('memory', 2048);
                  handleInputChange('vcpus', 2);
                }} 
              />
              <Chip 
                label="高性能: 4GB RAM, 4 vCPU" 
                size="small" 
                clickable 
                onClick={() => {
                  handleInputChange('memory', 4096);
                  handleInputChange('vcpus', 4);
                }} 
              />
            </Box>
          </Box>
        )}

        {/* 步骤3: 存储配置 */}
        {activeStep === 2 && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
            <TextField
              label="磁盘路径"
              value={formData.disk_path}
              onChange={(e) => handleInputChange('disk_path', e.target.value)}
              fullWidth
              placeholder="例如: /var/lib/libvirt/images/ubuntu-vm.qcow2"
              helperText="虚拟机磁盘文件的完整路径"
            />
            
            <TextField
              label="磁盘大小 (GB)"
              type="number"
              value={formData.disk_size}
              onChange={(e) => handleInputChange('disk_size', parseInt(e.target.value) || 0)}
              fullWidth
              helperText="虚拟磁盘的大小"
            />

            <FormControl fullWidth>
              <InputLabel>磁盘总线类型</InputLabel>
              <Select
                value={formData.disk_bus}
                onChange={(e) => handleInputChange('disk_bus', e.target.value)}
                label="磁盘总线类型"
              >
                <MenuItem value="virtio">VirtIO (推荐)</MenuItem>
                <MenuItem value="sata">SATA</MenuItem>
                <MenuItem value="scsi">SCSI</MenuItem>
              </Select>
            </FormControl>

            <Typography variant="body2" color="text.secondary">
              磁盘配置建议：
            </Typography>
            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              <Chip 
                label="轻量级: 10GB" 
                size="small" 
                clickable 
                onClick={() => handleInputChange('disk_size', 10)} 
              />
              <Chip 
                label="标准: 20GB" 
                size="small" 
                clickable 
                onClick={() => handleInputChange('disk_size', 20)} 
              />
              <Chip 
                label="大型: 50GB" 
                size="small" 
                clickable 
                onClick={() => handleInputChange('disk_size', 50)} 
              />
            </Box>
          </Box>
        )}

        {/* 步骤4: 网络配置 */}
        {activeStep === 3 && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
            <FormControl fullWidth>
              <InputLabel>网络模式</InputLabel>
              <Select
                value={formData.network_mode}
                onChange={(e) => handleInputChange('network_mode', e.target.value)}
                label="网络模式"
              >
                <MenuItem value="network">虚拟网络</MenuItem>
                <MenuItem value="bridge">桥接网络</MenuItem>
                <MenuItem value="user">用户模式网络</MenuItem>
              </Select>
            </FormControl>

            <TextField
              label="网络名称"
              value={formData.network_name}
              onChange={(e) => handleInputChange('network_name', e.target.value)}
              fullWidth
              placeholder="例如: default, virbr0"
              helperText="网络名称或网桥名称"
            />

            <Typography variant="body2" color="text.secondary">
              网络模式说明：
            </Typography>
            <Box sx={{ mt: 1 }}>
              <Typography variant="caption" display="block">
                • <strong>虚拟网络:</strong> 使用libvirt管理的虚拟网络，适合大多数场景
              </Typography>
              <Typography variant="caption" display="block">
                • <strong>桥接网络:</strong> 直接连接到物理网络，需要配置网桥
              </Typography>
              <Typography variant="caption" display="block">
                • <strong>用户模式:</strong> 使用SLIRP网络，无需特殊权限但性能较低
              </Typography>
            </Box>
          </Box>
        )}

        <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 4 }}>
          <Button
            disabled={activeStep === 0}
            onClick={handleBack}
            sx={{ minWidth: 100 }}
          >
            上一步
          </Button>
          {activeStep === steps.length - 1 ? (
            <Button
              variant="contained"
              onClick={handleSubmit}
              disabled={isSubmitting || loading}
              startIcon={isSubmitting || loading ? <CircularProgress size={20} /> : <SaveIcon />}
              sx={{ minWidth: 120 }}
            >
              {isSubmitting || loading ? '创建中...' : '创建虚拟机'}
            </Button>
          ) : (
            <Button
              variant="contained"
              onClick={handleNext}
              sx={{ minWidth: 100 }}
            >
              下一步
            </Button>
          )}
        </Box>
      </Paper>
    </Box>
  );
};

export default DomainCreate;